package cn.jinjimi.app.poster.activity;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.poster.bean.PosterInfo;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.poster.interfaces.IPosterLoadMore;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.bean.RouterConstants;
import cn.jinjimi.app.main.dialog.SharePosterFragment;
import cn.jinjimi.app.main.extend.BaseActivity;

import java.util.ArrayList;

/**
 * Created by lforxeverc on 2016/11/22.
 */

public class PosterDetailActivity extends BaseActivity implements View.OnClickListener {
    private String type;
    private TextView tvTitle;
    private RelativeLayout rlTitleHolder;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_poster_list);
    }

    @Override
    protected void initial() {
        rlTitleHolder = (RelativeLayout) findViewById(R.id.rl_title_holder);
        rlRefresh = (RelativeLayout) findViewById(R.id.rl_footer);
        tvRefresh = (TextView) findViewById(R.id.tv_refresh);
        tvTitle = (TextView) findViewById(R.id.tv_title_bar_title);
        findViewById(R.id.btn_left).setOnClickListener(this);
        showPosterDetail();
    }

    private void showPosterDetail() {
        refreshDistance = (int) (getResources().getDisplayMetrics().density * refreshDistance);
        String ids = getIntent().getStringExtra(BundleKey.PARAM_POSTER_IDS);
        String urls = getIntent().getStringExtra(BundleKey.PARAM_POSTER_THUMBNAIL_URL);
        String start = getIntent().getStringExtra(BundleKey.PARAM_POSTER_POSITION);
        type = getIntent().getStringExtra(BundleKey.TYPE);
        if (StringUtils.isEmpty(type))
            type = PosterListActivity.ROUTER_TYPE_POSTER;

        if (ids == null || ids.isEmpty()) return;
        String[] idArray = ids.split(",");
        if (idArray.length == 0) return;

        String[] urlArray = null;
        if (urls != null && !urls.isEmpty()) {
            urlArray = urls.split(",");
        }
        final ArrayList<PosterInfo> infos = new ArrayList<>();
        for (int i = 0; i < idArray.length; i++) {
            try {
                String idStr = idArray[i].trim();
                int id = Integer.parseInt(idStr);
                String url = (urlArray != null && urlArray.length > i) ? urlArray[i].trim() : null;
                PosterInfo info = new PosterInfo(url, id);
                infos.add(info);
            } catch (Exception e) {
            }
        }
        int position = 0;
        if (!StringUtils.isEmpty(start)) {
            position = Integer.parseInt(start);
            position = (0 > position || position >= infos.size()) ? 0 : position;
        }
        fragment = new SharePosterFragment();
        fragment.setContext(this);
        fragment.setLoadMoreListener(new IPosterLoadMore() {
            @Override
            public void reqLoadPage(int page) {
            }

            @Override
            public PosterInfo fetchPosterInfoWithPosition(int position) {
                return infos.get(position);
            }

            @Override
            public void updatePostInfo(PosterInfo info, int position) {
                infos.set(position, info);
            }
        });
        fragment.setInfos(position, infos.size());
        fragment.setStyle(SharePosterFragment.Style.Normal);
        if (StringUtils.isEmpty(type) || PosterListActivity.ROUTER_TYPE_POSTER.equals(type)) {
            fragment.setCategoryCode(PosterContainerFragment.DataType.INFORMATION_POSTER);
            tvTitle.setText(getString(R.string.poster));
        } else {
            fragment.setCategoryCode(PosterContainerFragment.DataType.JINJU_POSTER);
            tvTitle.setText(getString(R.string.dujinju));
        }

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fl_container, fragment);
        ft.commit();
    }

    @Override
    public void onClick(View v) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private ViewPager mVp;
    private RelativeLayout rlRefresh;
    float downX = 0;
    float offset = 0;
    boolean isLastPage = false;
    int refreshViewWidth;
    SharePosterFragment fragment;
    int refreshDistance = 30;
    TextView tvRefresh;
    boolean shouldEnterAty = false;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mVp = fragment.getVpPoster();
        //直接进入最后一张海报且直接左滑无法滑动bug
        isLastPage = mVp.getCurrentItem() == mVp.getAdapter().getCount() - 1;
        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                isLastPage = mVp.getAdapter().getCount() - 1 == position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        CheckBox view = fragment.getDisplayMarkView();
        if (view != null && rlTitleHolder.getChildCount() == 0) {
            if (view.getParent() instanceof ViewGroup) {
                ViewGroup parent = (ViewGroup) view.getParent();
                parent.removeView(view);
            }
            view.setBackground(getResources().getDrawable(R.drawable.selector_poster_add_personal_info));
            rlTitleHolder.addView(view);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (shouldEnterAty) {
            shouldEnterAty = false;
            rlRefresh.setX(getWindow().getDecorView().getWidth());
            mVp.setX(0);
        }
    }

    int contentWidth = 0;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (rlRefresh == null || mVp == null) return super.dispatchTouchEvent(ev);
        if (refreshViewWidth == 0)
            refreshViewWidth = rlRefresh.getWidth();
        if (isLastPage && !shouldEnterAty) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = ev.getX();
                    offset = 0;
                    if (contentWidth == 0)
                        contentWidth = getWindow().getDecorView().getWidth();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float cx = ev.getX();
                    offset = cx - downX;
                    rlRefresh.setX(contentWidth + offset);
                    tvRefresh.setText((-offset >= refreshDistance + refreshViewWidth ? "释放" : "左滑") + "查看更多" + (PosterListActivity.ROUTER_TYPE_POSTER.equals(type) ? "海报" : "金句"));
                    if (offset < 0) {
                        mVp.setX(offset);
                    }
                    break;
                default:

                    shouldEnterAty = -offset >= refreshDistance + refreshViewWidth;
                    if (shouldEnterAty) {
                        if (type.equals(PosterListActivity.ROUTER_TYPE_POSTER)) {
                            Intent i = new Intent(PosterDetailActivity.this, PosterListActivity.class);
                            i.putExtra(PosterListActivity.DELAY, "yes");
                            i.putExtra(BundleKey.TYPE, type);
                            startActivity(i);
                        } else if (type.equals(PosterListActivity.ROUTER_TYPE_JINJU)) {
                            Router.create(this, RouterConstants.getNativeRouter(RouterConstants.ReaderIndex)).addParam(BundleKey.POSITION, "1").open();
                        }
                    } else {
                        final ValueAnimator an = ValueAnimator.ofFloat(offset, 0);
                        an.setDuration(200);
                        an.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                float x = (float) animation.getAnimatedValue();
                                rlRefresh.setX(contentWidth + x);
                                if (x <= 0)
                                    mVp.setX(x);
                            }
                        });
                        an.start();
                    }
                    break;
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
